// 五子棋游戏主类
class GomokuGame {
    constructor() {
        this.canvas = document.getElementById('gameBoard');
        this.ctx = this.canvas.getContext('2d');
        this.boardSize = 15;
        this.cellSize = 40;
        this.board = [];
        this.currentPlayer = 1; // 1为黑棋，2为白棋
        this.gameMode = 'pvp';
        this.gameOver = false;
        this.moveCount = 0;
        this.gameStartTime = null;
        this.gameTimer = null;
        this.soundEnabled = true;
        this.soundVolume = 0.5;
        this.winningLine = null;
        this.lastMove = null;
        
        this.initializeBoard();
        this.setupEventListeners();
        this.setupCanvas();
        this.drawBoard();
        this.hideLoading();
    }

    // 初始化棋盘
    initializeBoard() {
        this.board = [];
        for (let i = 0; i < this.boardSize; i++) {
            this.board[i] = [];
            for (let j = 0; j < this.boardSize; j++) {
                this.board[i][j] = 0;
            }
        }
    }

    // 设置画布
    setupCanvas() {
        const size = this.boardSize * this.cellSize;
        this.canvas.width = size;
        this.canvas.height = size;
        this.canvas.style.width = size + 'px';
        this.canvas.style.height = size + 'px';
    }

    // 设置事件监听器
    setupEventListeners() {
        // 棋盘点击事件
        this.canvas.addEventListener('click', (e) => this.handleCanvasClick(e));
        this.canvas.addEventListener('mousemove', (e) => this.handleMouseMove(e));
        this.canvas.addEventListener('mouseleave', () => this.clearHover());

        // 按钮事件
        document.getElementById('newGame').addEventListener('click', () => this.newGame());
        document.getElementById('settingsBtn').addEventListener('click', () => this.showSettings());
        document.getElementById('helpBtn').addEventListener('click', () => this.showHelp());
        document.getElementById('closeSettings').addEventListener('click', () => this.hideSettings());
        document.getElementById('closeHelp').addEventListener('click', () => this.hideHelp());
        document.getElementById('playAgain').addEventListener('click', () => this.newGame());
        document.getElementById('backToMenu').addEventListener('click', () => this.hideGameOver());

        // 模式选择
        document.querySelectorAll('.mode-btn').forEach(btn => {
            btn.addEventListener('click', (e) => this.changeGameMode(e.target.dataset.mode));
        });

        // 主题选择
        document.querySelectorAll('.theme-btn').forEach(btn => {
            btn.addEventListener('click', (e) => this.changeTheme(e.target.dataset.theme));
        });

        // 音效控制
        document.getElementById('soundVolume').addEventListener('input', (e) => {
            this.soundVolume = e.target.value / 100;
        });

        document.getElementById('muteBtn').addEventListener('click', () => this.toggleSound());

        // 棋盘大小选择
        document.getElementById('boardSize').addEventListener('change', (e) => {
            this.changeBoardSize(parseInt(e.target.value));
        });

        // 键盘事件
        document.addEventListener('keydown', (e) => this.handleKeyPress(e));
    }

    // 处理画布点击
    handleCanvasClick(e) {
        if (this.gameOver) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        const col = Math.round(x / this.cellSize);
        const row = Math.round(y / this.cellSize);
        
        if (this.isValidMove(row, col)) {
            this.makeMove(row, col);
        }
    }

    // 处理鼠标移动（悬停效果）
    handleMouseMove(e) {
        if (this.gameOver) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        const col = Math.round(x / this.cellSize);
        const row = Math.round(y / this.cellSize);
        
        if (this.isValidMove(row, col)) {
            this.drawBoard();
            this.drawHoverPiece(row, col);
        }
    }

    // 清除悬停效果
    clearHover() {
        this.drawBoard();
    }

    // 绘制悬停棋子
    drawHoverPiece(row, col) {
        const x = col * this.cellSize;
        const y = row * this.cellSize;
        const radius = this.cellSize * 0.4;
        
        this.ctx.save();
        this.ctx.globalAlpha = 0.5;
        
        if (this.currentPlayer === 1) {
            this.ctx.fillStyle = '#000';
        } else {
            this.ctx.fillStyle = '#fff';
            this.ctx.strokeStyle = '#000';
            this.ctx.lineWidth = 2;
        }
        
        this.ctx.beginPath();
        this.ctx.arc(x, y, radius, 0, 2 * Math.PI);
        this.ctx.fill();
        
        if (this.currentPlayer === 2) {
            this.ctx.stroke();
        }
        
        this.ctx.restore();
    }

    // 检查是否为有效移动
    isValidMove(row, col) {
        return row >= 0 && row < this.boardSize && 
               col >= 0 && col < this.boardSize && 
               this.board[row][col] === 0;
    }

    // 执行移动
    makeMove(row, col) {
        this.board[row][col] = this.currentPlayer;
        this.lastMove = { row, col };
        this.moveCount++;
        
        // 播放音效
        this.playSound('move');
        
        // 更新界面
        this.updateMoveCount();
        this.drawBoard();
        
        // 添加棋子放置动画
        this.animatePiecePlace(row, col);
        
        // 检查游戏结束
        const winner = this.checkWinner(row, col);
        if (winner) {
            this.endGame(winner);
            return;
        }
        
        // 检查平局
        if (this.moveCount === this.boardSize * this.boardSize) {
            this.endGame(0); // 平局
            return;
        }
        
        // 切换玩家
        this.switchPlayer();
        
        // AI回合
        if (this.gameMode.startsWith('pve') && this.currentPlayer === 2) {
            setTimeout(() => this.makeAIMove(), 500);
        }
    }

    // AI移动
    makeAIMove() {
        let move;
        if (this.gameMode === 'pve-easy') {
            move = this.getRandomMove();
        } else {
            move = this.getBestMove();
        }
        
        if (move) {
            this.makeMove(move.row, move.col);
        }
    }

    // 获取随机移动（简单AI）
    getRandomMove() {
        const validMoves = [];
        for (let i = 0; i < this.boardSize; i++) {
            for (let j = 0; j < this.boardSize; j++) {
                if (this.board[i][j] === 0) {
                    validMoves.push({ row: i, col: j });
                }
            }
        }
        return validMoves[Math.floor(Math.random() * validMoves.length)];
    }

    // 获取最佳移动（困难AI）
    getBestMove() {
        // 简化的AI算法：优先级策略
        // 1. 检查是否能获胜
        // 2. 检查是否需要防守
        // 3. 选择最佳位置
        
        // 检查获胜机会
        for (let i = 0; i < this.boardSize; i++) {
            for (let j = 0; j < this.boardSize; j++) {
                if (this.board[i][j] === 0) {
                    this.board[i][j] = 2;
                    if (this.checkWinner(i, j)) {
                        this.board[i][j] = 0;
                        return { row: i, col: j };
                    }
                    this.board[i][j] = 0;
                }
            }
        }
        
        // 检查防守需要
        for (let i = 0; i < this.boardSize; i++) {
            for (let j = 0; j < this.boardSize; j++) {
                if (this.board[i][j] === 0) {
                    this.board[i][j] = 1;
                    if (this.checkWinner(i, j)) {
                        this.board[i][j] = 0;
                        return { row: i, col: j };
                    }
                    this.board[i][j] = 0;
                }
            }
        }
        
        // 选择中心附近的位置
        const center = Math.floor(this.boardSize / 2);
        const moves = [];
        
        for (let i = 0; i < this.boardSize; i++) {
            for (let j = 0; j < this.boardSize; j++) {
                if (this.board[i][j] === 0) {
                    const distance = Math.abs(i - center) + Math.abs(j - center);
                    moves.push({ row: i, col: j, distance });
                }
            }
        }
        
        moves.sort((a, b) => a.distance - b.distance);
        return moves[0];
    }

    // 检查获胜者
    checkWinner(row, col) {
        const player = this.board[row][col];
        const directions = [
            [0, 1],   // 水平
            [1, 0],   // 垂直
            [1, 1],   // 对角线
            [1, -1]   // 反对角线
        ];
        
        for (let [dx, dy] of directions) {
            let count = 1;
            let line = [{ row, col }];
            
            // 正方向
            for (let i = 1; i < 5; i++) {
                const newRow = row + dx * i;
                const newCol = col + dy * i;
                if (newRow >= 0 && newRow < this.boardSize && 
                    newCol >= 0 && newCol < this.boardSize && 
                    this.board[newRow][newCol] === player) {
                    count++;
                    line.push({ row: newRow, col: newCol });
                } else {
                    break;
                }
            }
            
            // 反方向
            for (let i = 1; i < 5; i++) {
                const newRow = row - dx * i;
                const newCol = col - dy * i;
                if (newRow >= 0 && newRow < this.boardSize && 
                    newCol >= 0 && newCol < this.boardSize && 
                    this.board[newRow][newCol] === player) {
                    count++;
                    line.unshift({ row: newRow, col: newCol });
                } else {
                    break;
                }
            }
            
            if (count >= 5) {
                this.winningLine = line.slice(0, 5);
                return player;
            }
        }
        
        return null;
    }

    // 切换玩家
    switchPlayer() {
        this.currentPlayer = this.currentPlayer === 1 ? 2 : 1;
        this.updatePlayerStatus();
    }

    // 更新玩家状态显示
    updatePlayerStatus() {
        const blackStatus = document.getElementById('blackStatus');
        const whiteStatus = document.getElementById('whiteStatus');
        const blackPlayer = document.querySelector('.black-player');
        const whitePlayer = document.querySelector('.white-player');
        
        if (this.currentPlayer === 1) {
            blackStatus.textContent = '当前回合';
            whiteStatus.textContent = '等待中';
            blackStatus.classList.add('active');
            whiteStatus.classList.remove('active');
            blackPlayer.classList.add('active');
            whitePlayer.classList.remove('active');
        } else {
            blackStatus.textContent = '等待中';
            whiteStatus.textContent = '当前回合';
            blackStatus.classList.remove('active');
            whiteStatus.classList.add('active');
            blackPlayer.classList.remove('active');
            whitePlayer.classList.add('active');
        }
    }

    // 更新步数显示
    updateMoveCount() {
        document.getElementById('moveCount').textContent = this.moveCount;
    }

    // 绘制棋盘
    drawBoard() {
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制背景
        this.drawBackground();
        
        // 绘制网格线
        this.drawGrid();
        
        // 绘制星位
        this.drawStarPoints();
        
        // 绘制棋子
        this.drawPieces();
        
        // 绘制最后一步标记
        this.drawLastMoveMarker();
        
        // 绘制获胜线
        if (this.winningLine) {
            this.drawWinningLine();
        }
    }

    // 绘制背景
    drawBackground() {
        const gradient = this.ctx.createLinearGradient(0, 0, this.canvas.width, this.canvas.height);
        gradient.addColorStop(0, '#DEB887');
        gradient.addColorStop(1, '#D2B48C');
        
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    }

    // 绘制网格线
    drawGrid() {
        this.ctx.strokeStyle = '#8B4513';
        this.ctx.lineWidth = 1;
        
        for (let i = 0; i < this.boardSize; i++) {
            const pos = i * this.cellSize;
            
            // 垂直线
            this.ctx.beginPath();
            this.ctx.moveTo(pos, 0);
            this.ctx.lineTo(pos, this.canvas.height);
            this.ctx.stroke();
            
            // 水平线
            this.ctx.beginPath();
            this.ctx.moveTo(0, pos);
            this.ctx.lineTo(this.canvas.width, pos);
            this.ctx.stroke();
        }
    }

    // 绘制星位
    drawStarPoints() {
        const starPoints = [];
        if (this.boardSize === 15) {
            starPoints.push([3, 3], [3, 11], [7, 7], [11, 3], [11, 11]);
        } else if (this.boardSize === 19) {
            starPoints.push([3, 3], [3, 9], [3, 15], [9, 3], [9, 9], [9, 15], [15, 3], [15, 9], [15, 15]);
        }
        
        this.ctx.fillStyle = '#8B4513';
        starPoints.forEach(([row, col]) => {
            const x = col * this.cellSize;
            const y = row * this.cellSize;
            this.ctx.beginPath();
            this.ctx.arc(x, y, 3, 0, 2 * Math.PI);
            this.ctx.fill();
        });
    }

    // 绘制棋子
    drawPieces() {
        for (let i = 0; i < this.boardSize; i++) {
            for (let j = 0; j < this.boardSize; j++) {
                if (this.board[i][j] !== 0) {
                    this.drawPiece(i, j, this.board[i][j]);
                }
            }
        }
    }

    // 绘制单个棋子
    drawPiece(row, col, player) {
        const x = col * this.cellSize;
        const y = row * this.cellSize;
        const radius = this.cellSize * 0.4;
        
        // 阴影效果
        this.ctx.save();
        this.ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
        this.ctx.shadowBlur = 5;
        this.ctx.shadowOffsetX = 2;
        this.ctx.shadowOffsetY = 2;
        
        if (player === 1) {
            // 黑棋
            const gradient = this.ctx.createRadialGradient(x - radius/3, y - radius/3, 0, x, y, radius);
            gradient.addColorStop(0, '#666');
            gradient.addColorStop(1, '#000');
            this.ctx.fillStyle = gradient;
        } else {
            // 白棋
            const gradient = this.ctx.createRadialGradient(x - radius/3, y - radius/3, 0, x, y, radius);
            gradient.addColorStop(0, '#fff');
            gradient.addColorStop(1, '#ddd');
            this.ctx.fillStyle = gradient;
        }
        
        this.ctx.beginPath();
        this.ctx.arc(x, y, radius, 0, 2 * Math.PI);
        this.ctx.fill();
        
        // 白棋边框
        if (player === 2) {
            this.ctx.strokeStyle = '#999';
            this.ctx.lineWidth = 1;
            this.ctx.stroke();
        }
        
        this.ctx.restore();
    }

    // 绘制最后一步标记
    drawLastMoveMarker() {
        if (!this.lastMove) return;
        
        const x = this.lastMove.col * this.cellSize;
        const y = this.lastMove.row * this.cellSize;
        
        this.ctx.strokeStyle = '#ff0000';
        this.ctx.lineWidth = 3;
        this.ctx.beginPath();
        this.ctx.arc(x, y, this.cellSize * 0.2, 0, 2 * Math.PI);
        this.ctx.stroke();
    }

    // 绘制获胜线
    drawWinningLine() {
        if (!this.winningLine || this.winningLine.length < 2) return;
        
        const start = this.winningLine[0];
        const end = this.winningLine[this.winningLine.length - 1];
        
        const startX = start.col * this.cellSize;
        const startY = start.row * this.cellSize;
        const endX = end.col * this.cellSize;
        const endY = end.row * this.cellSize;
        
        this.ctx.strokeStyle = '#FFD700';
        this.ctx.lineWidth = 5;
        this.ctx.lineCap = 'round';
        
        this.ctx.beginPath();
        this.ctx.moveTo(startX, startY);
        this.ctx.lineTo(endX, endY);
        this.ctx.stroke();
    }

    // 棋子放置动画
    animatePiecePlace(row, col) {
        const x = col * this.cellSize;
        const y = row * this.cellSize;
        
        gsap.fromTo(this.canvas, 
            { 
                filter: 'brightness(1.2)' 
            },
            { 
                filter: 'brightness(1)',
                duration: 0.3,
                ease: 'power2.out'
            }
        );
    }

    // 结束游戏
    endGame(winner) {
        this.gameOver = true;
        this.stopTimer();
        
        if (winner === 0) {
            this.playSound('draw');
            this.showGameOver('平局！', '棋盘已满，游戏平局！');
        } else {
            this.playSound('win');
            const winnerName = winner === 1 ? '黑棋' : '白棋';
            const winnerEmoji = winner === 1 ? '⚫' : '⚪';
            this.showGameOver(`${winnerName}获胜！`, `${winnerEmoji} 恭喜${winnerName}获得胜利！`);
        }
    }

    // 显示游戏结束面板
    showGameOver(title, message) {
        document.getElementById('gameOverTitle').textContent = title;
        document.getElementById('winnerDisplay').textContent = title.includes('黑棋') ? '⚫' : title.includes('白棋') ? '⚪' : '🤝';
        document.getElementById('gameSummary').innerHTML = `
            ${message}<br>
            游戏时长: ${this.getGameTime()}<br>
            总步数: ${this.moveCount}
        `;
        document.getElementById('gameOverModal').classList.add('show');
    }

    // 隐藏游戏结束面板
    hideGameOver() {
        document.getElementById('gameOverModal').classList.remove('show');
    }

    // 新游戏
    newGame() {
        this.initializeBoard();
        this.currentPlayer = 1;
        this.gameOver = false;
        this.moveCount = 0;
        this.winningLine = null;
        this.lastMove = null;
        this.hideGameOver();
        this.updatePlayerStatus();
        this.updateMoveCount();
        this.drawBoard();
        this.startTimer();
    }

    // 更改游戏模式
    changeGameMode(mode) {
        this.gameMode = mode;
        document.querySelectorAll('.mode-btn').forEach(btn => btn.classList.remove('active'));
        document.querySelector(`[data-mode="${mode}"]`).classList.add('active');
        this.newGame();
    }

    // 更改主题
    changeTheme(theme) {
        document.body.className = `theme-${theme}`;
        document.querySelectorAll('.theme-btn').forEach(btn => btn.classList.remove('active'));
        document.querySelector(`[data-theme="${theme}"]`).classList.add('active');
        this.drawBoard();
    }

    // 更改棋盘大小
    changeBoardSize(size) {
        this.boardSize = size;
        this.setupCanvas();
        this.newGame();
    }

    // 显示设置
    showSettings() {
        document.getElementById('settingsModal').classList.add('show');
    }

    // 隐藏设置
    hideSettings() {
        document.getElementById('settingsModal').classList.remove('show');
    }

    // 显示帮助
    showHelp() {
        document.getElementById('helpModal').classList.add('show');
    }

    // 隐藏帮助
    hideHelp() {
        document.getElementById('helpModal').classList.remove('show');
    }

    // 切换音效
    toggleSound() {
        this.soundEnabled = !this.soundEnabled;
        const btn = document.getElementById('muteBtn');
        btn.textContent = this.soundEnabled ? '🔊' : '🔇';
    }

    // 播放音效
    playSound(type) {
        if (!this.soundEnabled) return;
        
        // 这里可以添加实际的音效播放逻辑
        // 由于是演示，我们使用Web Audio API创建简单音效
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        switch (type) {
            case 'move':
                oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
                break;
            case 'win':
                oscillator.frequency.setValueAtTime(1200, audioContext.currentTime);
                break;
            case 'draw':
                oscillator.frequency.setValueAtTime(400, audioContext.currentTime);
                break;
        }
        
        gainNode.gain.setValueAtTime(this.soundVolume * 0.1, audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.1);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.1);
    }

    // 开始计时器
    startTimer() {
        this.gameStartTime = Date.now();
        this.gameTimer = setInterval(() => {
            const elapsed = Date.now() - this.gameStartTime;
            const minutes = Math.floor(elapsed / 60000);
            const seconds = Math.floor((elapsed % 60000) / 1000);
            document.getElementById('gameTimer').textContent = 
                `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }, 1000);
    }

    // 停止计时器
    stopTimer() {
        if (this.gameTimer) {
            clearInterval(this.gameTimer);
            this.gameTimer = null;
        }
    }

    // 获取游戏时间
    getGameTime() {
        if (!this.gameStartTime) return '00:00';
        const elapsed = Date.now() - this.gameStartTime;
        const minutes = Math.floor(elapsed / 60000);
        const seconds = Math.floor((elapsed % 60000) / 1000);
        return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }

    // 处理键盘事件
    handleKeyPress(e) {
        switch (e.key) {
            case 'Escape':
                this.hideSettings();
                this.hideHelp();
                this.hideGameOver();
                break;
            case 'n':
            case 'N':
                if (e.ctrlKey) {
                    e.preventDefault();
                    this.newGame();
                }
                break;
            case 'h':
            case 'H':
                if (e.ctrlKey) {
                    e.preventDefault();
                    this.showHelp();
                }
                break;
        }
    }

    // 隐藏加载动画
    hideLoading() {
        setTimeout(() => {
            const loadingOverlay = document.getElementById('loadingOverlay');
            loadingOverlay.classList.add('hidden');
            setTimeout(() => {
                loadingOverlay.style.display = 'none';
            }, 500);
        }, 1000);
    }
}

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    const game = new GomokuGame();
    
    // 添加页面可见性变化监听（防止后台运行时计时器继续）
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            game.stopTimer();
        } else if (game.gameStartTime && !game.gameOver) {
            game.startTimer();
        }
    });
});

// 防止右键菜单
document.addEventListener('contextmenu', (e) => {
    if (e.target.tagName === 'CANVAS') {
        e.preventDefault();
    }
});

// 防止选择文本
document.addEventListener('selectstart', (e) => {
    if (e.target.tagName === 'CANVAS') {
        e.preventDefault();
    }
});